﻿using System;
using JSONHelpers;
using System.Data.SqlClient;
using System.Globalization;
using System.Collections.Generic;


public partial class Ovnis : System.Web.UI.Page
{
    static string   _respuestaCache = "";           // cadena de respuesta cacheada aca
    static int      _ultimoAccesoDB = 0;            // cuando fue la última vez que accedí a la db?
    static object   _lock           = new object(); // para bloquear :)

    protected void Page_Load (object sender, EventArgs e)
    {
        Response.Write (dameOvnis());
    }

    string dameOvnis ()
    {
        //if ((_ultimoAccesoDB - Environment.TickCount) >= 1000)
        //{
        //    // consultar db
        //    // construir objeto json
        //    // crear cadena cache
        //}
        //return cadenaCache;

        JSONArray jarray = new JSONArray();

        using (SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=w1701119_televoyeurdb;Integrated Security=SSPI;"))
        {
            try
            {
                conn.Open();

                using (SqlDataReader sdr = new SqlCommand("select * from ovnis", conn).ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        JSONObject jobject = new JSONObject();

                        jobject.Add(new JSONFieldAtom("key", new JSONAtom(sdr["descr"])));
                        jobject.Add(new JSONFieldAtom("lat", new JSONAtom(((double)sdr["lat"]).ToString(CultureInfo.InvariantCulture.NumberFormat), true)));
                        jobject.Add(new JSONFieldAtom("lon", new JSONAtom(((double)sdr["lon"]).ToString(CultureInfo.InvariantCulture.NumberFormat), true)));
                        jobject.Add(new JSONFieldAtom("vel", new JSONAtom(((double)sdr["vel"]).ToString(CultureInfo.InvariantCulture.NumberFormat), true)));
                        jobject.Add(new JSONFieldAtom("bea", new JSONAtom(((double)sdr["bea"]).ToString(CultureInfo.InvariantCulture.NumberFormat), true)));
                        jarray.Add (jobject);
                    }
                }

                conn.Close();
                _ultimoAccesoDB = Environment.TickCount;
            }
            catch (Exception exx)
            {
                Response.Write(exx.Message);
            }
        }

        JSONObject obj = new JSONObject(
            new JSONFieldArray(
                "ovnis",
                jarray
            )
        );

        return obj.ToString();
    }
}
